#include "StompedReality/Asset/AssetManager.h"
#include "StompedReality/Asset/PatchSystem.h"
#include "StompedReality/Asset/TextureSystem.h"
#include "StompedReality/Core/GameAccess.h"
#include "StompedReality/Core/Logger.h"
namespace StompedReality {
namespace Asset {
AssetManager::AssetManager( ) :
  StompedReality::GameAccess( )
{
  this->m_PatchSystem = 0;
  this->m_TextureSystem = 0;
}

AssetManager::~AssetManager( )
{
  delete this->m_PatchSystem;
  delete this->m_TextureSystem;
}

void AssetManager::InitSubSystems( )
{
  this->m_TextureSystem = new TextureSystem( );
  this->m_TextureSystem->SetGame( this->m_Game );
  this->m_PatchSystem = new PatchSystem( );
  this->m_PatchSystem->SetGame( this->m_Game );
}

bool AssetManager::ParseConfig ( JsonPTR root )
{
  LogCallFunctionInfo( "AssetManager", "ParseConfig" );
  Json::Value amRoot = root->get( "AssetManager", 0 );

  // init texture system
  this->m_TextureSystem->Initialize( amRoot["TextureSystem"].get( "capacity", 128 ).asInt( ));

  // read texture files
  for (unsigned int i = 0; i < amRoot["TextureSystem"]["files"].size( ); ++i) {
    LogCallFunctionSubInfo( "read texture map" );
    LogInfoPair( "file", amRoot["TextureSystem"]["files"][i].asCString( ));

    this->m_TextureSystem->ReadFromFile( amRoot["TextureSystem"]["files"][i].asCString( ));
  }

  // init patch system
  this->m_PatchSystem->Initialize( amRoot["PatchSystem"].get( "capacity", 128 ).asInt( ));

  // read patch files
  for (unsigned int i = 0; i < amRoot["PatchSystem"]["files"].size( ); ++i) {
    LogCallFunctionSubInfo( "read patch map" );
    LogInfoPair( "file", amRoot["PatchSystem"]["files"][i].asCString( ));

    this->m_PatchSystem->ReadFromFile( amRoot["PatchSystem"]["files"][i].asCString( ));
  }

  return true;
}

const TextureInfo AssetManager::GetTextureInfo ( ID id )
{
  return this->m_TextureSystem->GetTextureInfo( id );
}

const ID AssetManager::GetGLTextureBindingID ( ID id )
{
  return this->m_TextureSystem->GetGLTextureBindingID( id );
}

bool AssetManager::HasTextureInfo ( ID id )
{
  return this->m_TextureSystem->HasTextureInfo( id );
}

const PatchInfo AssetManager::GetPatchInfo ( ID id )
{
  return this->m_PatchSystem->GetPatchInfo( id );
}

const ID AssetManager::GetGLPatchBindingID ( ID id )
{
  return this->m_PatchSystem->GetGLPatchBindingID( id );
}

bool AssetManager::HasPatchInfo ( ID id )
{
  return this->m_PatchSystem->HasPatchInfo( id );
}

bool AssetManager::OpenTexture ( StompedReality::Asset::TextureInfo& info, const char* fileName )
{
  return this->m_TextureSystem->OpenTexture( info, fileName );
}

}
}